package com.hdu.seckilldemo.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.hdu.seckilldemo.exception.GlobalException;
import com.hdu.seckilldemo.pojo.Order;
import com.hdu.seckilldemo.mapper.OrderMapper;
import com.hdu.seckilldemo.pojo.SeckillGoods;
import com.hdu.seckilldemo.pojo.SeckillOrder;
import com.hdu.seckilldemo.pojo.User;
import com.hdu.seckilldemo.service.IGoodsService;
import com.hdu.seckilldemo.service.IOrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hdu.seckilldemo.service.ISeckillGoodsService;
import com.hdu.seckilldemo.vo.GoodsVo;
import com.hdu.seckilldemo.vo.OrderDetailVo;
import com.hdu.seckilldemo.vo.RespBeanEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author lwy
 * @since 2023-02-09
 */
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements IOrderService {
    @Autowired
    private ISeckillGoodsService seckillGoodsService;
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private SeckillOrderServiceImpl seckillOrderService;
    @Autowired
    private IGoodsService goodsService;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     *  秒杀操作
     * @param user
     * @param goodsVo
     * @return
     */
    @Override
    @Transactional
    public Order seckill(User user, GoodsVo goodsVo) throws InterruptedException {
        ValueOperations valueOperations = redisTemplate.opsForValue();
        //1. 减库存
        // 1.1 从数据库中获取goods信息
        SeckillGoods goods = seckillGoodsService.getOne(new QueryWrapper<SeckillGoods>().eq("goods_id", goodsVo.getId()));
        //goods.setStockCount(goods.getStockCount()-1);
        // 超卖优化 1. 减完库存以后，判断库存是否大于0 ，如果大于0 才能更新
        // update stock_count = stock_count -1  where id = goods_id and stock_count > 0;
        boolean result = seckillGoodsService.update(new UpdateWrapper<SeckillGoods>().setSql("stock_count = stock_count - 1").eq("id", goods.getId()).gt("stock_count", 0));
        // 1.2 检查秒杀结果
        if(!result){
            // 优化 借助redis 将库存不足的商品添加到redis中
            valueOperations.set("isStockEmpty"+goods.getId(),"0");
            //如果没更新成功 直接返回null
            return null;
        }
        //2. 生成订单
        Order order = new Order();
        order.setUserId(user.getId());
        order.setGoodsId(goodsVo.getId());
        order.setGoodsName(goodsVo.getGoodsName());
        order.setGoodsCount(1);
        order.setGoodsPrice(goods.getSeckillPrice());
        order.setOrderChannel(1);
        order.setStatus(0);
        order.setCreateDate(new Date());
        orderMapper.insert(order);
        //3. 生成秒杀订单
        SeckillOrder seckillOrder = new SeckillOrder();
        seckillOrder.setUserId(user.getId());
        seckillOrder.setOrderId(order.getId());
        seckillOrder.setGoodsId(goodsVo.getId());
        seckillOrderService.save(seckillOrder);
        // 优化：将秒杀订单信息写入redis
        redisTemplate.opsForValue().set("order:"+user.getId()+":"+goods.getId(),seckillOrder);
        return order;
    }

    //订单详情
    @Override
    public OrderDetailVo detail(Long orderId) {
        if(orderId == null){
            //如果ID不存在 抛出异常
              throw new GlobalException(RespBeanEnum.ORDER_NOT_EXIST);
        }
        //查询订单
        Order order = orderMapper.selectById(orderId);
        //查询商品
        GoodsVo goods = goodsService.findGoodsVoByGoodsId(order.getGoodsId());
        //创建详情传输对象
        OrderDetailVo detailVo = new OrderDetailVo();
        detailVo.setOrder(order);
        detailVo.setGoodsVo(goods);
        return detailVo;
    }
}
